package com.wwz.multithreading;

/**
 * @description: 多线程打印ABC
 * @author: wwz
 * @date: 2023-12-17 10:42:12
 */
public class PrintABC {
    private static Integer num = 0;
    // 共享对象作为锁
    private static Object lock = new Object();

    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    try {
                        synchronized (lock) {
                            // 为什么这里为什么不能用if代替while？ 因为if可能会产生虚假唤醒
                            while (num % 3 != 0) {
                                lock.wait();
                            }
                            System.out.println("A");
                            num++;
                            lock.notifyAll();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 5; i++) {
                        synchronized (lock) {
                            while (num % 3 != 1) {
                                lock.wait();
                            }
                            System.out.println("B");
                            num++;
                            lock.notifyAll();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < 5; i++) {
                        synchronized (lock) {
                            while (num % 3 != 2) {
                                lock.wait();
                            }
                            System.out.println("C");
                            num++;
                            lock.notifyAll();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
        threadA.start();
        threadB.start();
        threadC.start();
    }
}
